package com.isoftstone.common.base;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.session.Session;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 类名称：
 *
 * @author：guoX
 * @date: 2016/6/6
 */
public class CustomMultipartResolver extends CommonsMultipartResolver {
   /* @Autowired
    private FileProcessListener fileProcessListener;*/
    private HttpServletRequest request;

//    protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
//        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
//        upload.setSizeMax(-1);
//        Session session = SecurityUtils.getSubject().getSession();
//        //HttpSession session = request.getSession();
//        FileProcessListener progressListener = new FileProcessListener(session);
//        upload.setProgressListener(progressListener);
//        return upload;
//    }

    public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
        // 获取到request,要用到session
        this.request = request;
        return super.resolveMultipart(request);
    }

    @Override
    public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        //HttpSession session = request.getSession();
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        Session session = SessionManager.getSession();
        FileProcessListener progressListener = new FileProcessListener(session);
        fileUpload.setProgressListener(progressListener);
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Could not parse multipart servlet request", ex);
        }
    }
}